package com.lib.fastkit.utils.px_dp;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.res.Configuration;
import android.util.DisplayMetrics;

import androidx.annotation.NonNull;

/**
 * px---像素点，dp---即dip，像素密度，dpi---每单位英寸的像素数，也叫做屏幕密度，density---密度限定符，表示当前屏幕的密度水平
 *
 * dpi = ((1920^2 + 1080^2)^ 1/2 ) / 5 = 440 即屏幕宽高(像素)分别平方相加再开平方，再除以屏幕尺寸，就是该手机的dpi
 *
 * px = density*dp;
 * density = dpi/160;
 * px = dp*(dpi/160)
 *
 * 今日头条屏幕适配方式
 *
 * 使用方式：
 * 当设计图的设计尺寸为360/480等时，里面控件的宽或者高有一定值，直接在XML中显示尺寸值
 * 在下面设计目标Density时，将具体360/480带入即可
 *
 */
public class ScreenAdaptationUtil {

    public static float aNoncompatDensity;
    public static float aNoncompatScaledDensity;

    public static void setCustomDensity(final Application application, Activity activity) {

        final DisplayMetrics appDisplayMetrics = application.getResources().getDisplayMetrics();
        if (aNoncompatDensity == 0) {
            aNoncompatDensity = appDisplayMetrics.density;
            aNoncompatScaledDensity = appDisplayMetrics.scaledDensity;
            application.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(@NonNull Configuration newConfig) {
                    if (newConfig.fontScale > 0) {
                        aNoncompatScaledDensity = application.getResources().getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {

                }
            });
        }

        final float targetDensity = (float) (appDisplayMetrics.widthPixels / 960);
        final float targetScaledDensity = targetDensity * (aNoncompatScaledDensity / aNoncompatDensity);
        final int targetDensityDpi = (int) (targetDensity * 160);

        //设置application的Density
        appDisplayMetrics.density = targetDensity;
        appDisplayMetrics.scaledDensity = targetScaledDensity;
        appDisplayMetrics.densityDpi = targetDensityDpi;

        //设置activity的Density
        final DisplayMetrics activityDisplayMetrics = activity.getResources().getDisplayMetrics();
        activityDisplayMetrics.density = targetDensity;
        activityDisplayMetrics.scaledDensity = targetScaledDensity;
        activityDisplayMetrics.densityDpi = targetDensityDpi;
    }

}
